import { Element, useEditor } from "@craftjs/core";
import { Tooltip } from "@mui/material";
import React, { useRef, useEffect } from "react";
import { styled } from "styled-components";
import Image from "next/image";
import ButtonSvg from "../../../public/icons/toolbox/button.svg";
import SquareSvg from "../../../public/icons/toolbox/rectangle.svg";
import TypeSvg from "../../../public/icons/toolbox/text.svg";
import YoutubeSvg from "../../../public/icons/toolbox/video-line.svg";
import { Button } from "../../selectors/Button";
import { Container } from "../../selectors/Container";
import { Text } from "../../selectors/Text";
import { ImageBox } from "../../selectors/ImageBox";
import { Img } from "../../selectors/Img";
import { Video } from "../../selectors/Video";
import { pasteSerializedNodesTree } from "../../../utils/fragment";
import PhotoIcon from "@mui/icons-material/Photo";
const ToolboxDiv = styled.div<{ $enabled: boolean }>`
	transition: 0.4s cubic-bezier(0.19, 1, 0.22, 1);
	${(props) => (!props.$enabled ? `width: 0;` : "")}
	${(props) => (!props.$enabled ? `opacity: 0;` : "")}
`;

const Item = styled.a<{ $move?: boolean }>`
	display: flex;
	align-items: center;
	justify-content: center;
	flex-direction: column;

	svg {
		width: 28px;
		height: 28px;
		fill: #707070;
	}
	${(props) =>
		props.$move &&
		`
    cursor: move;
  `}
`;
// 封装获取组件名方法（拖拽元素有可能是子元素无法获取到data-display-name的值）
function getDisplayName(node: Node) {
	// @ts-ignore
	const displayName = node.dataset.displayName;
	if (displayName) {
		return displayName;
	}
	if (node.parentNode) {
		return getDisplayName(node.parentNode);
	}
	return "";
}
export const Toolbox = () => {
	const {
		enabled,
		connectors: { create },
		connectors,
		query,
		actions,
	} = useEditor((state) => ({
		enabled: state.options.enabled,
	}));
	// 拖拽区域父节点
	const containerRef = useRef(null);
	useEffect(() => {
		// 拖拽开始
		const dragstart = (e) => {
			// 不要打开下面注释，会导致编辑器异常
			// e.preventDefault();
			// 给根节点设置自定义属性
			actions.setCustom("ROOT", (data) => {
				// 由于使用事件代理所以多数情况下e.target并不是
				// 设置data-display-name的div，因此使用getDisplayName方法
				data.DraggerEl = getDisplayName(e.target);
			});
		};
		if (containerRef.current) {
			// 事件代理的形式监听事件
			containerRef.current.addEventListener("dragstart", dragstart);
		}

		return () => {
			// 注销监听事件
			if (containerRef.current) {
				containerRef.current.removeEventListener("dragstart", dragstart);
			}
		};
	}, [containerRef]);

	return (
		<ToolboxDiv
			$enabled={enabled && enabled}
			className="toolbox transition w-24 h-full flex bg-white"
			ref={containerRef}
		>
			<div className="flex flex-1 flex-col items-center pt-3 gap-3">
				<div
					ref={(ref) => {
						create(
							ref,
							<Element
								canvas
								is={Container}
								background={{ r: 78, g: 78, b: 78, a: 1 }}
								color={{ r: 0, g: 0, b: 0, a: 1 }}
								height="300px"
								width="300px"
							></Element>
						);
					}}
					// 使用此属性标注当前拖拽的组件
					data-display-name="Container"
				>
					<Tooltip title="Container" placement="right">
						<Item $move>
							<SquareSvg viewBox="-3 -3 24 24" />
						</Item>
					</Tooltip>
				</div>
				<div
					ref={(ref) => {
						create(
							ref,
							<Text fontSize="12" textAlign="left" text="Hi there" />
						);
					}}
					// 使用此属性标注当前拖拽的组件
					data-display-name="Text"
				>
					<Tooltip title="Text" placement="right">
						<Item $move>
							<TypeSvg viewBox="-3 -3 28 28" />
						</Item>
					</Tooltip>
				</div>
				<div
					ref={(ref) => {
						create(ref, <Button />);
					}}
					data-display-name="Button"
				>
					<Tooltip title="Button" placement="right">
						<Item $move>
							<ButtonSvg viewBox="-4 -3 24 24" />
						</Item>
					</Tooltip>
				</div>
				<div
					ref={(ref) => {
						create(ref, <Video />);
					}}
					data-display-name="Video"
				>
					<Tooltip title="Video" placement="right">
						<Item $move>
							<YoutubeSvg viewBox="-3 -3 28 28" />
						</Item>
					</Tooltip>
				</div>
				<div
					ref={(ref) => {
						connectors.create(ref, () => {
							// 模拟获取数据
							const data = JSON.parse(localStorage.getItem("fragment"));
							return pasteSerializedNodesTree(query, data);
						});
					}}
					data-display-name=""
				>
					片段
				</div>
				<div
					ref={(ref) => {
						create(ref, <ImageBox />);
					}}
					data-display-name="ImageBox"
				>
					<Tooltip title="图片" placement="right">
						<Item $move>
							<PhotoIcon viewBox="-3 -3 28 28" />
						</Item>
					</Tooltip>
				</div>
			</div>
			{/* 此区域是图片资源 */}
			<div className="flex flex-1 flex-col items-center pt-3 gap-3">
				<div
					ref={(ref) => {
						create(
							ref,
							<Img src="https://mui.com/static/material-ui/react-components/autocomplete-light.png" />
						);
					}}
					data-display-name="Img"
				>
					<Image
						width={50}
						height={50}
						src="https://mui.com/static/material-ui/react-components/autocomplete-light.png"
						alt=""
					/>
				</div>
				<div
					ref={(ref) => {
						create(
							ref,
							<Img src="https://mui.com/static/material-ui/react-components/button-light.png" />
						);
					}}
					data-display-name="Img"
				>
					<Image
						width={50}
						height={50}
						src="https://mui.com/static/material-ui/react-components/button-light.png"
						alt=""
					/>
				</div>
			</div>
		</ToolboxDiv>
	);
};
